<script setup lang="ts">
import { reactive, computed, onMounted } from 'vue'
import { useRouter } from "vue-router";
// import { storage } from '../utils/storage';
import { useUserStore } from '../store/modules/user'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import CryptoJS from 'crypto-js';
interface FormState {
  username: string;
  password: string;
  rememberMe:Boolean;
  loginLoading: Boolean
}
const formState = reactive<FormState>({
  username: '',
  password: '',
  rememberMe: true,
  loginLoading: false
});
const router = useRouter();
const userStore = useUserStore()
console.log(userStore.Token)
onMounted(() => {
  // 获取记住的密码
  window.electron.ipcRenderer.invoke('get-user-info').then(res => {
    console.log(res)
    if(res.success) {
      if(res.userInfo) {
        formState.username = res.userInfo.username
        formState.password = decrypt(res.userInfo.password)
      }
    } else {
      console.log('失败',res.message)
    }
  })
  // 获取mac地址
  window.electron.ipcRenderer.invoke('mac-address').then((res) => {
    if(res.success) {
      console.log('成功',res.data)
    } else {
      console.log('失败',res.message)
    }
  })
})
// 加密
const encrypt = (password) => {
  return CryptoJS.AES.encrypt(password, '123456').toString();
};
// 解密
const decrypt = (encryptedPassword) => {
  const bytes = CryptoJS.AES.decrypt(encryptedPassword, '123456');
  return bytes.toString(CryptoJS.enc.Utf8);
};
const onFinish = (values: any) => {
  formState.loginLoading = true
  console.log('Success:', values);
  let obj = {
     "account": values.username,
     "password": values.password
  }
  console.log('obj',obj, formState)
  userStore.login(obj).then((res) => {
    console.log('res',res)
    formState.loginLoading = false
    if (formState.rememberMe) {
      localStorage.setItem('username', values.username);
      localStorage.setItem('password', values.password);
      window.electron.ipcRenderer.invoke('set-user-info', { username: values.username, password: encrypt(values.password) }).then(res => {
        console.log(res)
        if(res.success) {
          console.log('成功')
        } else {
          console.log('失败',res.message)
        }
      })
    } else {
      localStorage.removeItem('username');
      localStorage.removeItem('password');
      window.electron.ipcRenderer.invoke('clear-user-info').then(res => {
        console.log(res)
        if(res.success) {
          console.log('删除成功')
        } else {
          console.log('删除失败',res.message)
        }
      })
    }
    router.push('/')
  }).catch(err => {
    console.log('err',err)
    formState.loginLoading = false
  })
  // userStore.Token = 'xxxxxxxxxxxxxxxxxxabcd'
  // storage.set('Auth-Token', `xxxxxxxxxxxxxxxxxxabcd`) // token
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
  formState.loginLoading = false
};
const disabled = computed(() => {
  return !(formState.username && formState.password);
});

</script>

<template>
  <div class="login">
    <a-form
        :model="formState"
        class="login-form"
        name="horizontal_login"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
    >
        <div class="logo-">
          <img class="img" src="../assets/logo.png" alt="">
        </div>
        <a-form-item
            label="账户"
            name="username"
            :rules="[{ required: true, message: 'Please input your username!' }]"
            >
            <a-input v-model:value="formState.username">
                <template #prefix>
                <UserOutlined class="site-form-item-icon" />
                </template>
            </a-input>
        </a-form-item>

        <a-form-item
            label="密码"
            name="password"
            :rules="[{ required: true, message: 'Please input your password!' }]"
            >
            <a-input-password v-model:value="formState.password">
                <template #prefix>
                <LockOutlined class="site-form-item-icon" />
                </template>
            </a-input-password>
        </a-form-item>
        <a-form-item style="text-align: right;">
          <a-form-item name="remember" no-style>
            <a-checkbox v-model:checked="formState.rememberMe">记住密码</a-checkbox>
          </a-form-item>
        </a-form-item>
        <a-form-item style="text-align: center;">
            <a-button :disabled="disabled" type="primary" html-type="submit" :loading="formState.loginLoading">登 录</a-button>
            
        </a-form-item>
        <!-- <a-button type="primary" @click="$router.push('/')">去首页</a-button> -->
    </a-form>
  </div>
</template>

<style scoped>
.login{
  width: 300px;
  margin: auto;
  color: #fff;
  height: 100%;
  display: flex;
  /* flex-direction: column; */
  align-items: center;
}
.logo-{
  margin:auto;
  text-align: center;
}
.img{
  height: 80px;
  margin-bottom: 20px;
}
</style>